package com.aiapphub.BaseCode.service.impl;

import com.aiapphub.BaseCode.entity.Menu;
import com.aiapphub.BaseCode.mapper.MenuMapper;
import com.aiapphub.BaseCode.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单管理服务实现类
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getMenuTree() {
        // 获取所有菜单
        List<Menu> allMenus = menuMapper.selectAllMenus();
        // 构建树形结构
        return buildMenuTree(allMenus);
    }

    @Override
    public List<Menu> getUserMenus(Long userId) {
        List<Menu> userMenus = menuMapper.selectMenuListByUserId(userId);
        return buildMenuTree(userMenus);
    }

    @Override
    public boolean saveMenu(Menu menu) {
        menu.setCreateTime(new Date());
        menu.setUpdateTime(new Date());
        menu.setIsDeleted(0);
        // 设置菜单层级
        if (menu.getParentId() == 0) {
            menu.setLevel(1);
        } else {
            Menu parentMenu = this.getById(menu.getParentId());
            if (parentMenu != null) {
                menu.setLevel(parentMenu.getLevel() + 1);
            } else {
                menu.setLevel(1);
            }
        }
        return this.save(menu);
    }

    @Override
    public boolean updateMenu(Menu menu) {
        menu.setUpdateTime(new Date());
        return this.updateById(menu);
    }

    @Override
    public boolean removeMenu(Long menuId) {
        // 检查是否有子菜单
        if (hasChildren(menuId)) {
            throw new RuntimeException("该菜单下有子菜单，无法删除");
        }
        // 检查是否被角色使用
        if (isMenuUsedByRole(menuId)) {
            throw new RuntimeException("该菜单已被角色使用，无法删除");
        }
        return this.removeById(menuId);
    }

    @Override
    public boolean hasChildren(Long menuId) {
        return this.count(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Menu>()
                .eq("parent_id", menuId)
                .eq("is_deleted", 0)) > 0;
    }

    @Override
    public boolean isMenuUsedByRole(Long menuId) {
        List<Long> usedMenuIds = menuMapper.selectMenuIdsByRoleId(menuId);
        return usedMenuIds != null && !usedMenuIds.isEmpty();
    }
    
    /**
     * 根据角色ID获取菜单ID列表
     */
    @Override
    public List<Long> getMenuIdsByRoleId(Long roleId) {
        return menuMapper.selectMenuIdsByRoleId(roleId);
    }

    /**
     * 构建菜单树形结构
     */
    private List<Menu> buildMenuTree(List<Menu> menus) {
        // 将菜单按父ID分组
        Map<Long, List<Menu>> menuMap = menus.stream()
                .filter(menu -> menu.getMenuType() != 2) // 过滤掉按钮类型
                .collect(Collectors.groupingBy(Menu::getParentId));

        // 找到所有根节点（父ID为0的菜单）
        List<Menu> rootMenus = menuMap.getOrDefault(0L, new ArrayList<>());

        // 递归构建树形结构
        buildTree(rootMenus, menuMap);

        return rootMenus;
    }

    /**
     * 递归构建树形结构
     */
    private void buildTree(List<Menu> menus, Map<Long, List<Menu>> menuMap) {
        for (Menu menu : menus) {
            List<Menu> children = menuMap.getOrDefault(menu.getId(), new ArrayList<>());
            if (!children.isEmpty()) {
                // 对子菜单进行排序
                children.sort(Comparator.comparingInt(Menu::getSort));
                menu.setChildren(children);
                buildTree(children, menuMap);
            }
        }
    }
}